package com.ys.service.business.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import com.ys.entity.base.TbPlatform;
import com.ys.util.AESUtil;
import com.ys.util.StringUtil;
import com.ys.util.dhecp.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.config.MyConfig;
import com.ys.dto.AddDto;
import com.ys.dto.EditDto;
import com.ys.entity.amazonorder.TpAmazonShopOrderDaily;
import com.ys.entity.base.TbSite;
import com.ys.entity.business.TpAmazonSeller;
import com.ys.entity.business.TpAmazonShop;
import com.ys.entity.sys.TbStaticConfig;
import com.ys.enume.business.TpAmazonSellerEnum;
import com.ys.mapper.business.DiySqlMapper;
import com.ys.mapper.business.TpAmazonSellerMapper;
import com.ys.mapper.business.TpAmazonShopMapper;
import com.ys.service.business.TpAmazonShopService;
import com.ys.util.HttpUtilYs;
import com.ys.util.RandomUtil;
import com.ys.vo.R;

@Service("tpAmazonShopService")
public class TpAmazonShopServiceImpl implements TpAmazonShopService {

	private static final Logger logger = LoggerFactory.getLogger(TpAmazonShopServiceImpl.class);

	@Autowired
	private DiySqlMapper diySqlMapper;

	@Autowired
	private TpAmazonSellerMapper tpAmazonSellerMapper;
	@Autowired
	private TpAmazonShopMapper tpAmazonShopMapper;

	@Override
	public R listAll() {
		
		diySqlMapper.updateRegionCodeOfShop();
		
		List<TpAmazonShop> listTpAmazonShop = new TpAmazonShop()
				.where("(A.ShopName LIKE '%GB%' OR A.ShopName LIKE '%US%')")
				.queryList();
		
		List<ListAllDto.RowDto> rows = new ArrayList<ListAllDto.RowDto>();
		for(TpAmazonShop tpAmazonShop : listTpAmazonShop) {
			String guid = tpAmazonShop.getGuid();
			String shopUser = tpAmazonShop.getShopUser();
			String shopName = tpAmazonShop.getShopName();
			String sellerId = tpAmazonShop.getSellerId();
			rows.add(new ListAllDto.RowDto(guid, shopUser, shopName, sellerId));
		}
		
		ListAllDto dto = new ListAllDto(rows);
		return R.ok(dto);
	}
	
	@Override
	public R add(Long amazonSellerId, String detailArr) {
		TpAmazonSeller tpAmazonSeller = new TpAmazonSeller().setId(amazonSellerId).queryFirst();
		if (tpAmazonSeller == null) {
			return R.error("卖家信息不能为空");
		}

		/*
		 *  验证详情数据物料
		 *  1、站点ID不能为空
		 *  2、同个卖家站点不能重复
		 */
		JSONArray detailJA = JSON.parseArray(detailArr);
		if (detailJA == null || detailJA.size() == 0) {
			return R.error("详情数据不能为空");
		}
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);

			Long siteId = detailJO.getLong("siteId");
			if (siteId == null) {
				return R.error("站点ID不能为空");
			}

			if(new TpAmazonShop().setSellerId(tpAmazonSeller.getSellerId()).setSiteId(siteId).count() > 0) {
				return R.error("站点所在国家【" + detailJO.getString("countryName") + "】已存在");
			}
			String regex ="^[\\w\\d]+\\S";
			Pattern pattern = Pattern.compile(regex);
			if (!StringUtils.isEmpty(detailJO.getString("euAgent"))){
				if (!pattern.matcher(detailJO.getString("euAgent")).find() ){
					return R.error("欧盟代理人只允许英文字母加数字!");
				}
			}
			if (!StringUtils.isEmpty(detailJO.getString("euAgentAddress"))) {
				if (!pattern.matcher(detailJO.getString("euAgentAddress")).find()) {
					return R.error("欧盟代理地址只允许英文字母加数字!");
				}
			}
			if (!StringUtils.isEmpty(detailJO.getString("manufacturer"))) {
				if (!pattern.matcher(detailJO.getString("manufacturer")).find()) {
					return R.error("制造商只允许英文字母加数字!");
				}
			}
			if (!StringUtils.isEmpty(detailJO.getString("manufacturerAddress"))) {
				if (!pattern.matcher(detailJO.getString("manufacturerAddress")).find()) {
					return R.error("制造商地址只允许英文字母加数字!");
				}
			}
		}
		
		// 添加店铺
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);
			
			
			String guid = RandomUtil.getGUID();
			String shopUser = detailJO.getString("shopUser");
			String shopName = detailJO.getString("shopName");
			Long siteId = detailJO.getLong("siteId");
			String vat = detailJO.getString("vat");
			String eori = detailJO.getString("eori");
			String districtOrCounty = detailJO.getString("districtOrCounty");
			String name = detailJO.getString("name");
			String addressLine1 = detailJO.getString("addressLine1");
			String addressLine2 = detailJO.getString("addressLine2");
			String city = detailJO.getString("city");
			String stateOrProvinceCode = detailJO.getString("stateOrProvinceCode");
			String postalCode = detailJO.getString("postalCode");
			String phone = detailJO.getString("phone");
			String firstSaleDay = detailJO.getString("firstSaleDay");
			String euAgent = detailJO.getString("euAgent");
			String euAgentAddress = detailJO.getString("euAgentAddress");
			String manufacturer = detailJO.getString("manufacturer");
			String manufacturerAddress = detailJO.getString("manufacturerAddress");
			Integer euStatus = Integer.valueOf(detailJO.getString("euStatus"));
			TpAmazonShop entity = TpAmazonShop.tpAmazonShop(
					guid, shopUser, shopName, tpAmazonSeller.getSellerId(), siteId,
					vat, eori, districtOrCounty, name, addressLine1,
					addressLine2, city, stateOrProvinceCode, postalCode, phone,
					firstSaleDay, euAgent,euAgentAddress,manufacturer,manufacturerAddress,euStatus,tpAmazonSeller.getId(),1);
			tpAmazonShopMapper.insert(entity);
		}

		return R.ok(AddDto.closeAndReload());
	}

	@Override
	public R edit(Long amazonSellerId, String detailArr) {

		TpAmazonSeller tpAmazonSeller = new TpAmazonSeller().setId(amazonSellerId).queryFirst();
		if (tpAmazonSeller == null) {
			return R.error("卖家信息不能为空");
		}

		/*
		 *  验证详情数据物料
		 *  1、站点ID不能为空
		 *  2、同个卖家站点不能重复
		 */
		JSONArray detailJA = JSON.parseArray(detailArr);
		if (detailJA == null || detailJA.size() == 0) {
			return R.error("详情数据不能为空");
		}
		List<Long> idList = new ArrayList<>();
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);

			Long siteId = detailJO.getLong("siteId");
			if (siteId == null) {
				return R.error("站点ID不能为空");
			}
			Long id = detailJO.getLong("id");

			if (id != null){
				idList.add(id);
			}

			if(new TpAmazonShop().setSellerId(tpAmazonSeller.getSellerId()).setSiteId(siteId).where("A.amazonSellerId != " + tpAmazonSeller.getId()).count() > 0) {
				return R.error("站点所在国家【" + detailJO.getString("countryName") + "】已存在");
			}

			String regex ="^[\\w\\d]+\\S";
			Pattern pattern = Pattern.compile(regex);
			if (!StringUtils.isEmpty(detailJO.getString("euAgent"))){
				if (!pattern.matcher(detailJO.getString("euAgent")).find() ){
					return R.error("欧盟代理人只允许英文字母加数字!");
				}
			}
			if (!StringUtils.isEmpty(detailJO.getString("euAgentAddress"))) {
				if (!pattern.matcher(detailJO.getString("euAgentAddress")).find()) {
					return R.error("欧盟代理地址只允许英文字母加数字!");
				}
			}
			if (!StringUtils.isEmpty(detailJO.getString("manufacturer"))) {
				if (!pattern.matcher(detailJO.getString("manufacturer")).find()) {
					return R.error("制造商只允许英文字母加数字!");
				}
			}
			if (!StringUtils.isEmpty(detailJO.getString("manufacturerAddress"))) {
				if (!pattern.matcher(detailJO.getString("manufacturerAddress")).find()) {
					return R.error("制造商地址只允许英文字母加数字!");
				}
			}
		}

		List<TpAmazonShop> tpAmazonShopList = new TpAmazonShop().setAmazonSellerId(tpAmazonSeller.getId()).queryList();
		for (TpAmazonShop tpAmazonShop : tpAmazonShopList){
			if (!idList.contains(tpAmazonShop.getId())){
				tpAmazonShopMapper.deleteTrue(tpAmazonShop.getId());
			}
		}

		// 添加店铺
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);

			Long siteId = detailJO.getLong("siteId");
			Long id = detailJO.getLong("id");

			TpAmazonShop entity = null;
			if (id != null){
				entity = new TpAmazonShop().setId(id).queryFirst();
			}

			String guid = RandomUtil.getGUID();
			String shopUser = detailJO.getString("shopUser");
			String shopName = detailJO.getString("shopName");
			String vat = detailJO.getString("vat");
			String eori = detailJO.getString("eori");
			String districtOrCounty = detailJO.getString("districtOrCounty");
			String name = detailJO.getString("name");
			String addressLine1 = detailJO.getString("addressLine1");
			String addressLine2 = detailJO.getString("addressLine2");
			String city = detailJO.getString("city");
			String stateOrProvinceCode = detailJO.getString("stateOrProvinceCode");
			String postalCode = detailJO.getString("postalCode");
			String phone = detailJO.getString("phone");
			String firstSaleDay = detailJO.getString("firstSaleDay");
			String euAgent = detailJO.getString("euAgent");
			String euAgentAddress = detailJO.getString("euAgentAddress");
			String manufacturer = detailJO.getString("manufacturer");
			String manufacturerAddress = detailJO.getString("manufacturerAddress");
			Integer euStatus = Integer.valueOf(detailJO.getString("euStatus"));
			if (entity == null) {
				entity = TpAmazonShop.tpAmazonShop(
						guid, shopUser, shopName, tpAmazonSeller.getSellerId(), siteId,
						vat, eori, districtOrCounty, name, addressLine1, addressLine2, city, stateOrProvinceCode, postalCode, phone, firstSaleDay,
						euAgent,euAgentAddress,manufacturer,manufacturerAddress,euStatus,tpAmazonSeller.getId(),1);
				tpAmazonShopMapper.insert(entity);
			} else {
				entity
					.setShopUser(shopUser)
					.setShopName(shopName)
					.setSellerId(tpAmazonSeller.getSellerId())
					.setSiteId(siteId)
					.setVat(vat)
					.setEori(eori)
					.setDistrictOrCounty(districtOrCounty)
					.setName(name)
					.setAddressLine1(addressLine1)
					.setAddressLine2(addressLine2)
					.setCity(city)
					.setStateOrProvinceCode(stateOrProvinceCode)
					.setPostalCode(postalCode)
					.setPhone(phone)
					.setFirstSaleDay(firstSaleDay)
					.setEuAgent(euAgent)
					.setEuAgentAddress(euAgentAddress)
					.setManufacturer(manufacturer)
					.setManufacturerAddress(manufacturerAddress)
					.setEuStatus(euStatus)
				;
				tpAmazonShopMapper.update(entity);
			}
		}

		return R.ok(EditDto.closeAndReload());
	}

	@Override
	public R getAmazonAuthUrl(Long shopId) {
		TbStaticConfig tbStaticConfig = new TbStaticConfig().setKeyOne("amazon-spapi-application_id").queryFirst();
		try {
			if (shopId == null) {
				return R.error("卖家ID不能为空");
			}
			TpAmazonShop tpAmazonShop = new TpAmazonShop().setId(shopId).queryFirst();
			TbSite tbSite = new TbSite().setId(tpAmazonShop.getSiteId()).queryFirst();
			TpAmazonSeller tpAmazonSeller = new TpAmazonSeller().setSellerId(tpAmazonShop.getSellerId()).queryFirst();
			if (tpAmazonSeller == null){
				return R.error("卖家不存在");
			}

			/*
			 *  授权链接格式示例：
			 *  https://sellercentral.amazon.co.uk/apps/authorize/consent?application_id=amzn1.sp.solution.ad316d2c-89c0-4b6c-99f8-94ae5bbab11a&state=6ffd99eb-2be6-4dba-9487-9c5242adba16&version=beta
			 */
			String spApiAuthUrl = tbSite.getAmazonAuthUrlMj() + "/apps/authorize/consent?application_id=" + tbStaticConfig.getName() + "&state=" + shopId + "&version=beta";
			return R.ok(spApiAuthUrl);
		}catch (Exception e){
			e.printStackTrace();
			return R.error("ECP_API生成亚马逊授权URL地址出错，具体错误信息为："+e.getMessage());
		}
	}

	@Override
	public R getAmazonAuthUrlGg(Long shopId) {
		TbStaticConfig tbStaticConfig = new TbStaticConfig().setKeyOne("amazon-adsapi-client_id").queryFirst();
		try {
			if (shopId == null) {
				return R.error("卖家ID不能为空");
			}
			TpAmazonShop tpAmazonShop = new TpAmazonShop().setId(shopId).queryFirst();
			TbSite tbSite = new TbSite().setId(tpAmazonShop.getSiteId()).queryFirst();
			TpAmazonSeller tpAmazonSeller = new TpAmazonSeller().setSellerId(tpAmazonShop.getSellerId()).queryFirst();
			if (tpAmazonSeller == null){
				return R.error("卖家不存在");
			}

			/*
			 *  授权链接格式示例：
			 *  https://www.amazon.com/ap/oa?client_id=amzn1.application-oa2-client.9e5f750f27ba4ac4aea62bcca1f19fa6&scope=advertising::campaign_management&response_type=code&redirect_uri=https://admin.mini-ease.com/api/amazon/amazonAuthCallbackGg&state=8167
			 *  https://www.amazon.com/ap/oa?client_id=amzn1.application-oa2-client.9e5f750f27ba4ac4aea62bcca1f19fa6&scope=advertising::campaign_management&response_type=code&state=869724a3-c303-433a-8d5e-5982425a6fba
			 */
			String adsApiAuthUrl = tbSite.getAmazonPreAuthUrlGg() + "client_id=" + tbStaticConfig.getName() + "&scope=advertising::campaign_management&response_type=code&redirect_uri=" + MyConfig.getUrlDomain() + "/api/outer/notify/notifyFromAmazonAdsApi&state=" + shopId;
			return R.ok(adsApiAuthUrl);
		}catch (Exception e){
			e.printStackTrace();
			return R.error("ECP_API生成亚马逊广告授权URL地址出错，具体错误信息为："+e.getMessage());
		}
	}

	@Override
	public R getAmazonToken(String spapi_oauth_code, Long shopId) {
		TbStaticConfig tbStaticConfig3 = new TbStaticConfig().setKeyOne("amazon-spapi-lwa-end_point").queryFirst();
		//平台
		TbPlatform tbPlatform = new TbPlatform().setCode("PTBM001").queryFirst();
		if (tbPlatform == null){
			logger.error("获取亚马逊TOKEN失败，具体原因为TB_Platform平台PTBM001不存在!");
			return R.error("获取亚马逊TOKEN失败，具体原因为TB_Platform平台PTBM001不存在!");
		}
		String encryptSecret = AESUtil.aesDecrypt(tbPlatform.getEncryptSecret());
		try {
			if (spapi_oauth_code == null) {
				R.error("参数code不能为空！");
			}

			//String postParams = String.format("grant_type=authorization_code&code=%s&client_id=%s&client_secret=%s", code, ApiConfig.getAmazonLwaClientKey(), ApiConfig.getAmazonLwaClientSecret());
			Map<String, String> postMapParams = new HashMap<>();
			postMapParams.put("grant_type", "authorization_code");
			postMapParams.put("code", spapi_oauth_code);
			postMapParams.put("client_id", MyConfig.getAmazonLwaClientKey());
			postMapParams.put("client_secret", encryptSecret);

			System.out.println(JSON.toJSONString(postMapParams));

			String urlNotify = tbStaticConfig3.getName();
			/*
			 * 请求地址示例：
			 * https://api.amazon.com/auth/o2/token
			 * 请求失败结果示例：
			 * {"error_index":"uxqfeauTlVzH1S5tIg38ewAAAAAAAAABgQ1Dt_uHRH_PARxt5Ad9Q6JNN41dDtJmo16LvayCoSaOi1utfCi3YSnuDeLZm4WB7k4qlt3fTpfZ5PMCOh7B98zFsgn1RF9MGYQaOIfjNvhmD7uLL8ozKTDCTgAwmf2-4p6BNCv0S0AmU8XNLkY5lSJOQTkePDIeTen_nJThYMMbBqkLo0zuFkBtVoq4dRx0lR2DcVpx7yoz6wE3pGuvZrvgi8qfcNAU1HeVCQ==","error_description":"The request has an invalid grant parameter : code","error":"invalid_grant","request_id":"ce400a67-7ac3-4b0c-a406-f197a4ac980b"}
			 * 请求成功结果示例：
			 * {"access_token":"Atza|IwEBIBcS7vZTQgO9aLUr3aE5Bho9LFufEu_G0rhND-bOwLRZM35poX3ZGc0FRfAQTe7l6kxU2dOZK1J_YYM6NDUjdrCDbtisNCRabXwyuJw_OxlF5nQjt2T4AtiuLXEbwCKTFRszGf2X7Ich3xcT1zKYjzHw-2prspAkqT88r_P46Qo2SmgdykY1ID-wUpnALMQGXsH17425f2-SzmJbHCTxwsH1sQojr4phdc29yCxu27RFSwdgitSSSVGLIulFz9q8ex2A01C61btcgiylGtQIJH9xQBvgq3pKT8H2_KTGrYSNb8NLe8jhB2rJfCaXtHARkfQ","refresh_token":"Atzr|IwEBIK-J7VmMl9L6VmoVm8T9wYs6kAl-f4xURtFlnRXJm_FQfykw273p0_v3B7aB8z9cqEJSyv7l6XOL9e-yacVep0HRNtzPv5NvImlobSYidcWPPjhwxdEMLu4GD0zY5FNNNyxKcmBB17ZyGTycbIP4Sg_AyaleQ4rvSWSIZtAqulIWYVvyotxeT_roT6mIgbjTXj2uCZSOv2FfuQDTNmewnVlXjA2udJ9HXkqeH7ILHcwuq7JUgxAf4hpjpSa7__b4YR-xLN_JGIOoqgB0iA3pzdJnb_dmLQkBTkdo0qfRX6byHghZzsGQak0tlHfsgDDaLMzZcC7hLdWsxAogEoQ7TZBn","token_type":"bearer","expires_in":3600}
			 */
			String result = HttpUtilYs.sendHttpClientPost(urlNotify, postMapParams);
			System.out.println(result);
			JSONObject resultJO = JSON.parseObject(result);
			if (resultJO != null) {
				String error = resultJO.containsKey("error") ? resultJO.getString("error") : null;
				if (error == null || error.length() == 0){
					String access_token = resultJO.getString("access_token");
					String refresh_token = resultJO.getString("refresh_token");

					TpAmazonShop shop = new TpAmazonShop().setId(shopId).queryFirst();
					List<TpAmazonSeller> sellerList = new TpAmazonSeller().setSellerId(shop.getSellerId()).queryList();
					for (TpAmazonSeller seller : sellerList){
						seller
								.setAuthorizeState("已授权")
								.setAuthState(TpAmazonSellerEnum.AuthState.YES.value)
								.setAccessToken(access_token)
								.setRefreshToken(refresh_token)
								.setAuthState(TpAmazonSellerEnum.AuthState.YES.value);
						tpAmazonSellerMapper.update(seller);
					}


					return R.ok();
				}else{
					String errorDescription = resultJO.getString("error_description");
					return R.error("获取亚马逊TOKEN失败，具体原因为"+errorDescription);
				}
			}else{
				return R.error("获取亚马逊TOKEN失败！");
			}
		}catch (Exception e){
			e.printStackTrace();
			logger.error("ECP_API获取亚马逊授权TOKEN出错，错误信息为：" + e.getMessage());
		}
		return R.ok();
	}

	@Override
	public R getAmazonTokenGg(String code, Long shopId) {
		TbStaticConfig tbStaticConfig1 = new TbStaticConfig().setKeyOne("amazon-adsapi-client_id").queryFirst();
		TbStaticConfig tbStaticConfig2 = new TbStaticConfig().setKeyOne("amazon-adsapi-client_secret").queryFirst();
		try {
			if (code == null) {
				R.error("参数code不能为空！");
			}

			//String postParams = String.format("grant_type=authorization_code&code=%s&client_id=%s&client_secret=%s", code, ApiConfig.getAmazonLwaClientKey(), ApiConfig.getAmazonLwaClientSecret());
			Map<String, String> postMapParams = new HashMap<>();
			postMapParams.put("grant_type", "authorization_code");
			postMapParams.put("code", code);
			postMapParams.put("client_id", tbStaticConfig1.getName());
			postMapParams.put("client_secret", tbStaticConfig2.getName());
            postMapParams.put("redirect_uri", MyConfig.getUrlDomain() + "/api/outer/notify/notifyFromAmazonAdsApi");

			TpAmazonShop shop = new TpAmazonShop().setId(shopId).queryFirst();
			TpAmazonSeller seller = new TpAmazonSeller().setSellerId(shop.getSellerId()).queryFirst();
			TbSite tbSite = new TbSite().setId(shop.getSiteId()).queryFirst();
			System.out.println(JSON.toJSONString(postMapParams));
			/*
			 * 请求地址示例：
			 * https://api.amazon.com/auth/o2/token
			 * 请求失败结果示例：
			 * {"error_index":"uxqfeauTlVzH1S5tIg38ewAAAAAAAAABgQ1Dt_uHRH_PARxt5Ad9Q6JNN41dDtJmo16LvayCoSaOi1utfCi3YSnuDeLZm4WB7k4qlt3fTpfZ5PMCOh7B98zFsgn1RF9MGYQaOIfjNvhmD7uLL8ozKTDCTgAwmf2-4p6BNCv0S0AmU8XNLkY5lSJOQTkePDIeTen_nJThYMMbBqkLo0zuFkBtVoq4dRx0lR2DcVpx7yoz6wE3pGuvZrvgi8qfcNAU1HeVCQ==","error_description":"The request has an invalid grant parameter : code","error":"invalid_grant","request_id":"ce400a67-7ac3-4b0c-a406-f197a4ac980b"}
			 * 请求成功结果示例：
			 * {"access_token":"Atza|IwEBIBcS7vZTQgO9aLUr3aE5Bho9LFufEu_G0rhND-bOwLRZM35poX3ZGc0FRfAQTe7l6kxU2dOZK1J_YYM6NDUjdrCDbtisNCRabXwyuJw_OxlF5nQjt2T4AtiuLXEbwCKTFRszGf2X7Ich3xcT1zKYjzHw-2prspAkqT88r_P46Qo2SmgdykY1ID-wUpnALMQGXsH17425f2-SzmJbHCTxwsH1sQojr4phdc29yCxu27RFSwdgitSSSVGLIulFz9q8ex2A01C61btcgiylGtQIJH9xQBvgq3pKT8H2_KTGrYSNb8NLe8jhB2rJfCaXtHARkfQ","refresh_token":"Atzr|IwEBIK-J7VmMl9L6VmoVm8T9wYs6kAl-f4xURtFlnRXJm_FQfykw273p0_v3B7aB8z9cqEJSyv7l6XOL9e-yacVep0HRNtzPv5NvImlobSYidcWPPjhwxdEMLu4GD0zY5FNNNyxKcmBB17ZyGTycbIP4Sg_AyaleQ4rvSWSIZtAqulIWYVvyotxeT_roT6mIgbjTXj2uCZSOv2FfuQDTNmewnVlXjA2udJ9HXkqeH7ILHcwuq7JUgxAf4hpjpSa7__b4YR-xLN_JGIOoqgB0iA3pzdJnb_dmLQkBTkdo0qfRX6byHghZzsGQak0tlHfsgDDaLMzZcC7hLdWsxAogEoQ7TZBn","token_type":"bearer","expires_in":3600}
			 */
			String result = HttpUtilYs.sendHttpClientPost(tbSite.getAmazonAuthUrlGg(), postMapParams);
			System.out.println(result);
			JSONObject resultJO = JSON.parseObject(result);
			if (resultJO != null) {
				String error = resultJO.containsKey("error") ? resultJO.getString("error") : null;
				if (error == null || error.length() == 0){
					String access_token = resultJO.getString("access_token");
					String refresh_token = resultJO.getString("refresh_token");
					
					
					seller
						.setAuthorizeStateGg("已授权")
						.setAccessTokenGg(access_token)
						.setRefreshTokenGg(refresh_token)
						.setAuthStateGg(TpAmazonSellerEnum.AuthState.YES.value);
					tpAmazonSellerMapper.update(seller);

					return R.ok();
				}else{
					String errorDescription = resultJO.getString("error_description");
					return R.error("获取亚马逊TOKEN失败，具体原因为"+errorDescription);
				}
			}else{
				return R.error("获取亚马逊TOKEN失败！");
			}
		}catch (Exception e){
			e.printStackTrace();
			logger.error("ECP_API获取亚马逊授权TOKEN出错，错误信息为：" + e.getMessage());
		}
		return R.ok();
	}

	@Override
	public void updateFirstSaleDay(Long id) {
		TpAmazonShop entity = new TpAmazonShop().setId(id).queryFirst();
		if (entity.getFirstSaleDay() != null && entity.getFirstSaleDay().length() > 0) {
			return;
		}
		
		// 查找店铺的首单时间
		TpAmazonShopOrderDaily first = new TpAmazonShopOrderDaily()
				.setShopId(id)
				.setOrderby("A.DayPurchase asc")
				.queryFirst();
		if (first != null) {
			entity.setFirstSaleDay(first.getDayPurchase());
			tpAmazonShopMapper.update(entity);
		}
	}
}
